package fr.snac.widget;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.RemoteViews;
import fr.snac.bm.BonjourActivity;
import fr.snac.bm.R;
import fr.snac.utils.DateUtil;
import fr.snac.utils.FilesUtil;

public class WidgetReceiver extends AppWidgetProvider{
	
	private String imageDate;
	private Uri madameUri;
	private RemoteViews rV;
	
	
	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
		
		AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, CountDownReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		
		am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60, pi);
	}
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		
		imageDate = FilesUtil.getLastPicture();
		
		if (rV == null)
			rV = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
		
		if (FilesUtil.imageAlreadyDownloaded(imageDate)){

			File image = new File(FilesUtil.getImageFolderPath() + "/" + imageDate + FilesUtil.getImageType(imageDate));

			madameUri = Uri.fromFile(image);
			try {
				Bitmap bmp = MediaStore.Images.Media.getBitmap(context.getContentResolver(), madameUri);
				rV.setImageViewBitmap(R.id.widgetImage, bmp);
				//Log.d("WIDGETRECEIVER", "image updated");
			} catch (FileNotFoundException e) {
				//do Nothing
			} catch (IOException e) {
				//do Nothing
			}
			image = null; 
			
			rV.setImageViewUri(R.id.widgetImage, madameUri);
		}
		
		rV.setTextViewText(R.id.textWidget, DateUtil.getCountDown());
		
		
		
		Intent bm = new Intent(context, BonjourActivity.class);		
		PendingIntent pbm = PendingIntent.getActivity(context, 0, bm, 0);
		
		rV.setOnClickPendingIntent(R.id.widgetImage, pbm);
		
		for (int widgetId : appWidgetIds){
			appWidgetManager.updateAppWidget(widgetId, rV);
		}
	}
}
